package com.gba.mark.elasticsearch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gba.mark.elasticsearch.entity.OriginESCn;
import com.gba.mark.elasticsearch.entity.OriginESEn;
import com.gba.mark.elasticsearch.service.OriginESService;
import com.gba.mark.origin.entity.Origin;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class OriginESServiceImpl implements OriginESService {
    @Resource
    private RestHighLevelClient client;

    @Override
    public void bulkAddOriginESFromMySQL(List<Origin> originList, String index, String type) {
        int size = originList.size();
        System.out.println(size);
        int pointsDataLimit = 1000;
        if (size > pointsDataLimit) {
            int part = size / pointsDataLimit;
            for (int i = 0; i < part; i++) {
                BulkRequest bulkRequest = new BulkRequest();
                List<Origin> subOrigin = originList.subList(i, pointsDataLimit);
                for (Origin o : subOrigin) {
                    OriginESEn oes = new OriginESEn();
                    oes.setOrigin_id(o.getId());
                    oes.setSource(o.getSystem_label());
                    oes.setLanguage(o.toString());
                    oes.setSentence(o.getSentence());
                    IndexRequest indexRequest = new IndexRequest(index, type);
                    indexRequest.source(JSONObject.toJSONString(oes), XContentType.JSON);
                    bulkRequest.add(indexRequest);
                }
                originList.subList(0, pointsDataLimit).clear();
                try {
                    client.bulk(bulkRequest, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}



